﻿using System;
using System.Threading;

namespace TShooter.TfsSearch.EngineModel
{
    public abstract class ServiceBase: IService
    {
        #region Constructors and Member variables

        private const int THREAD_FINISH_TIMEOUT = 10000;
        private readonly ManualResetEvent _ManualResetEvent = new ManualResetEvent(true);
        private readonly Thread _Thread;
        private bool _EndTask;
        private int _PauseTimeout;

        protected ServiceBase()
        {
            _Thread = new Thread(BackgroundMethod);
        }

        #endregion

        #region Abstract members

        protected abstract bool DoService();
        public abstract string Name { get; }

        #endregion

        #region IService Members

        public event EventHandler Finished;

        public bool IsActive
        {
            get { return _Thread.IsAlive; }
        }

        public void Start()
        {
            _Thread.Name = Name;
            _Thread.Start();
        }

        public void Stop()
        {
            if (_EndTask && _Thread.IsAlive)
            {
                _EndTask = true;
                if (!_Thread.Join(THREAD_FINISH_TIMEOUT))
                {
                    _Thread.Abort();
                }
            }
            OnFinished();
        }

        public void Pause(int autoResumeMillisecs)
        {
            _PauseTimeout = autoResumeMillisecs <= 0? -1: autoResumeMillisecs;
            _ManualResetEvent.Reset();
        }

        public void Resume()
        {
            _ManualResetEvent.Set();
        }

        public ThreadPriority Priority
        {
            get { return _Thread.Priority; }
            set { _Thread.Priority = value; }
        }

        #endregion

        #region Private Methods

        private void BackgroundMethod()
        {
            while (DoService() && !_EndTask)
            {
                _ManualResetEvent.WaitOne(_PauseTimeout, false);
            }
            _EndTask = true;
            Stop();
        }

        protected virtual void OnFinished()
        {
            if (Finished != null)
            {
                Finished(this, EventArgs.Empty);
            }
        }

        #endregion
    }
}
